<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <!-- <el-form-item label="过期时间 0 不限制  1,2,3天数" prop="expirationTime">
        <el-input v-model="queryParams.expirationTime" placeholder="请输入过期时间 0 不限制  1,2,3天数" clearable
          @keyup.enter="handleQuery" />
      </el-form-item> -->
      <el-form-item label="用户名称" prop="userName">
        <el-input v-model="queryParams.userName" placeholder="请输入用户名字" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <!-- <el-form-item label="是否失效" prop="delFlag">
        <el-select v-model="queryParams.delFlag" placeholder="" clearable>
          <el-option v-for="(item,index) in token_status" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd"
          v-hasPermi="['sysUserToken:userToken:add']">获取token</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['sysUserToken:userToken:edit']">修改</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['sysUserToken:userToken:remove']">批量失效</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['sysUserToken:userToken:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <div>
      <Table ref="pageTableRef" :table-data="userTokenList" :border="true" size="small" :loading="loading"
        :columns="columns" :is-pagination="true" :selection="true" :show-index="true" :total="total" tableHeight="900"
        :current-page="queryParams.pageNum" :page-size="queryParams.pageSize" @changeSize="handleSizeChange"
        @changeCurrent="handleCurrentChange" @handleSelectionChange="handleSelectionChange" :selectTable="true" :selectableFun="selectable">
        <!-- <template #default="scope">
          <span @click="handleCopy(scope.row.token)" style="color: #409eff;cursor: pointer;">{{scope.row.token}}</span>
        </template> -->
        <template #expirationTime="scope">
          <div :style="{color: scope.row.delFlag == '0' ? scope.row.expirationTime == 0 ? '#95d475' : scope.row.expirationTime > 0 ? '#79bbff'
                  : '' : ''}">
            {{scope.row.expirationTime == 0 ? '无过期期限' : scope.row.expirationTime > 0 ? scope.row.expirationTime + '天后过期'
            : '--'}}
          </div>
        </template>
        <template #expirationDate="scope">
          <div>
            {{scope.row.expirationTime ? scope.row.expirationTime : '--'}}
          </div>
        </template>
        <template #delFlag="scope">
          <dict-tag :options="token_status" :value="scope.row.delFlag" />
        </template>
        <template #action="scope">
          <!-- <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                    v-hasPermi="['sysUserToken:userToken:edit']">修改</el-button> -->
          <el-button link type="primary" :disabled="scope.row.delFlag == 2" @click="handleDelete(scope.row)"
            v-hasPermi="['sysUserToken:userToken:remove']">失效</el-button>
        </template>
      </Table>
    </div>
    <!-- token_status -->
    <!-- <pagination v-show="total>0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
      @pagination="getList" /> -->
    <!-- 添加或修改用户token对话框 -->
    <el-dialog :title="title" v-model="open" width="500px">
      <el-form ref="userTokenRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="过期时间" prop="expirationTime">
          <el-input v-model="form.expirationTime" placeholder="过期时间0不限制,1,2,3...,天数不能为空" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="UserToken">
  import { listUserToken, getUserToken, delUserToken, addUserToken, updateUserToken } from "@/api/sysUserToken/userToken"

  const { proxy } = getCurrentInstance()
  const { data_del } = proxy.useDict('data_del')
  const { token_status } = proxy.useDict('token_status')

  const userTokenList = ref([])
  const open = ref(false)
  const buttonLoading = ref(false)
  const loading = ref(true)
  const showSearch = ref(true)
  const ids = ref([])
  const single = ref(true)
  const multiple = ref(true)
  const total = ref(0)
  const title = ref("")
  const tokenTable = ref()
  const selectable = ref((row,index) => {
    return row.delFlag == 0
  })
  const data = reactive({
    form: {},
    queryParams: {
      pageNum: 1,
      pageSize: 100,
      expirationTime: undefined,
    },
    rules: {
      userId: [
        { required: true, message: "用户ID不能为空", trigger: "blur" }
      ],
      token: [
        { required: true, message: "不能为空", trigger: "blur" }
      ],
      expirationTime: [
        { required: true, message: "过期时间0不限制,1,2,3...,天数不能为空", trigger: "blur" }
      ],
    }
  })
  const columns = ref([
    {
      prop: 'userId',
      label: '用户ID',
      minWidth: 150,
      align: 'center',
      showOverflowTooltip: true,
    },
    {
      prop: 'userName',
      label: '用户名',
      minWidth: 150,
      align: 'center',
      showOverflowTooltip: true,
    },
    {
      prop: 'token',
      label: 'token',
      minWidth: 150,
      isClick: true,
      align: 'center',
      showOverflowTooltip: true,
    },
    {
      prop: 'expirationTime',
      label: '过期时间',
      slot: 'expirationTime',
      minWidth: 150,
      align: 'center',
      showOverflowTooltip: true,
    },
    {
      prop: 'expirationDate',
      label: '设置天数',
      slot: 'expirationDate',
      minWidth: 150,
      align: 'center',
      showOverflowTooltip: true,
    },
    {
      prop: 'delFlag',
      label: '是否失效',
      slot: 'delFlag',
      minWidth: 150,
      align: 'center',
      showOverflowTooltip: true,
    },
    {
      prop: 'createTime',
      label: '创建时间',
      minWidth: 150,
      align: 'center',
      showOverflowTooltip: true,
    },
    {
      fixed: 'right',
      slot: 'action',
      label: '操作',
      minWidth: 150,
      align: 'center'
    }
  ])
  // 点击复制
  const handleCopy = (row) => {
    proxy.clickCopyFun(row)
  }
  const { queryParams, form, rules } = toRefs(data)

  /** 查询用户token列表 */
  function getList() {
    loading.value = true
    listUserToken(queryParams.value).then(response => {
      userTokenList.value = response.rows
      total.value = response.total
      loading.value = false
    })
  }

  // 取消按钮
  function cancel() {
    open.value = false
    reset()
  }

  // 表单重置
  function reset() {
    form.value = {
      userId: null,
      token: null,
      delFlag: null,
      expirationTime: null,
      createBy: null,
      createTime: null
    }
    proxy.resetForm("userTokenRef")
  }

  /** 搜索按钮操作 */
  function handleQuery() {
    queryParams.value.pageNum = 1
    getList()
  }

  /** 重置按钮操作 */
  function resetQuery() {
    proxy.resetForm("queryRef")
    handleQuery()
  }

  // // 多选框选中数据
  // function handleSelectionChange(selection) {
  //   ids.value = selection.map(item => item.userId)
  //   single.value = selection.length != 1
  //   multiple.value = !selection.length
  // }
  const handleSizeChange = (val) => {
    queryParams.value.pageSize = val
    getList()
  }
  const handleCurrentChange = (val) => {
    // console.log(val,'ABCDEFG-handleCurrentChange');
    queryParams.value.pageNum = val
    // console.log(queryParams.value, 'ABCDEFG-queryParams.value');
    getList()
  }
  const handleSelectionChange = (selection) => {
    // selection.value = val
    // ids.value = val.map(item => item.dataId)
    // single.value = val.length != 1
    // multiple.value = !val.length
    // ids.value = selection.map(item => item.classificationId)
    // single.value = selection.length != 1
    // multiple.value = !selection.length
    ids.value = selection.map(item => item.userId)
    single.value = selection.length != 1
    multiple.value = !selection.length
    // console.log(selection.value, 'ABCDEFG-handleSelectionChange')
  }
  // const selectable = (row, index) => {
  //   // console.log(tokenTable.value.selection,'selectable');
  //   // const selectArr = this.$refs.tableData.selection//获取选中行
  //   // const state = selectArr.some((item) => item.selectable == row.selectable)
  //   console.log(row, 'selectable');
  //   return row.delFlag == 0
  //   // const state = ids.value.map((item) => item.delFlag == 0 )
  //   // return state
  // }
  /** 新增按钮操作 */
  function handleAdd() {
    reset()
    open.value = true
    title.value = "获取token"
  }

  /** 修改按钮操作 */
  function handleUpdate(row) {
    loading.value = true
    reset()
    const _userId = row.userId || ids.value
    getUserToken(_userId).then(response => {
      loading.value = false
      form.value = response.data
      open.value = true
      title.value = "修改用户token"
    })
  }

  /** 提交按钮 */
  function submitForm() {
    proxy.$refs["userTokenRef"].validate(valid => {
      if (valid) {
        buttonLoading.value = true
        if (form.value.userId != null) {
          updateUserToken(form.value).then(response => {
            proxy.$modal.msgSuccess("修改成功")
            open.value = false
            getList()
          }).finally(() => {
            buttonLoading.value = false
          })
        } else {
          addUserToken(form.value).then(response => {
            proxy.$modal.msgSuccess("新增成功")
            open.value = false
            getList()
          }).finally(() => {
            buttonLoading.value = false
          })
        }
      }
    })
  }

  /** 删除按钮操作 */
  function handleDelete(row) {
    const _userIds = row.userId || ids.value
    // '是否确认删除用户token编号为"' + _userIds + '"的数据项？'
    proxy.$modal.confirm('是否确认失效用户token编号为"' + _userIds + '"的token？').then(function () {
      loading.value = true
      return delUserToken(_userIds)
    }).then(() => {
      loading.value = true
      getList()
      proxy.$modal.msgSuccess("成功")
    }).catch(() => {
    }).finally(() => {
      loading.value = false
    })
  }

  /** 导出按钮操作 */
  function handleExport() {
    proxy.download('sysUserToken/userToken/export', {
      ...queryParams.value
    }, `userToken_${new Date().getTime()}.xlsx`)
  }

  getList();
</script>
<style lang="scss" scoped>
  :deep() {
    .el-dialog {
      display: flex;
      flex-direction: column;
      margin: 0 !important;
      position: absolute;
      top: 40%;
      left: 50%;
      transform: translate(-50%, -40%);
      max-height: calc(100% - 60px);
      max-width: calc(100% - 30px);
    }

    .el-dialog .el-dialog__body {
      flex: 1;
      overflow: auto;
    }
  }
</style>
